package com.maben.million_insert.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.maben.million_insert.pojo.CirRootPO;
import com.maben.million_insert.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * 测试控制类
 */
@RestController
@Slf4j(topic = "m.TestController")
public class TestController {
    @Resource
    private AsyncService asyncService;

    /**
     * 测试百万写入
     */
    @RequestMapping("test_insert_million")
    public Map<String, Object> testInsertMillion(int totalSize) {
        final Map<String, Object> result = new HashMap<>();
        result.put("code", "1");
        result.put("msg", "insert million success.");
        result.put("startTime", DateUtil.now());
        try {
            if (totalSize<=0){
                throw new Exception("totalSize是正整数");
            }
            //多少条执行存储
            final int scale = 500;
            CountDownLatch countDownLatch = new CountDownLatch(totalSize % scale == 0 ? totalSize / scale : totalSize / scale + 1);
            final List<CirRootPO> cirRootPOList = new ArrayList<>();
            for (int i = 0; i < totalSize; i++) {
                final CirRootPO cirRootPO = getCirRootPO();
                cirRootPOList.add(cirRootPO);
                if (i > 0 && i % 500 == 0) {
                    log.info("handle save i:{}", i);
                    //这里使用新的集合，防止异步线程获取到的集合为空
                    final List<CirRootPO> tmp = new ArrayList<>(cirRootPOList);
                    asyncService.executeAsync(tmp, countDownLatch);
                    cirRootPOList.clear();
                }
            }
            if (cirRootPOList.size() > 0) {
                asyncService.executeAsync(cirRootPOList, countDownLatch);
            }
            //保证之前的所有的线程都执行完成，才会走下面的
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", -1);
            result.put("msg", ExceptionUtils.getStackTrace(e));
        }
        result.put("endTime", DateUtil.now());
        log.info("result:{}", JSON.toJSONString(result));
        return result;
    }

    /**
     * 获取实体类
     */
    private CirRootPO getCirRootPO() {
        final CirRootPO cirRootPO = new CirRootPO();
        cirRootPO.setId(UUID.randomUUID().toString().replace("-", ""));
        cirRootPO.setFrameHeaderHexStr("00");
        cirRootPO.setContentLengthInt(11);
        cirRootPO.setSourcePortHexStr("00");
        cirRootPO.setSourceAddressHexStr("00");
        cirRootPO.setTargetPortHexStr("00");
        cirRootPO.setTargetAddressHexStr("00");
        cirRootPO.setBusinessTypeHexStr("00");
        cirRootPO.setCmdHexStr("00");
        cirRootPO.setLoadHexStr("00");
        cirRootPO.setCrcCheckCodeHexStr("00");
        cirRootPO.setFrameFooterHexStr("00");
        cirRootPO.setTime(new Date());
        cirRootPO.setDeviceBcdStr("00");
        cirRootPO.setEnBcdStr("00");
        cirRootPO.setLineName("xxx");
        cirRootPO.setTnBcdStr("00");
        cirRootPO.setSynchronizationUnitId(UUID.randomUUID().toString().replace("-", ""));
        return cirRootPO;
    }

}
